from mcp.server.fastmcp import FastMCP

# 创建MCP服务器实例
mcp = FastMCP("计算器服务")

@mcp.tool()
def add(a: float, b: float) -> float:
    """两数相加"""
    return a + b

@mcp.tool()
def subtract(a: float, b: float) -> float:
    """两数相减"""
    return a - b

@mcp.tool()
def multiply(a: float, b: float) -> float:
    """两数相乘"""
    return a * b

@mcp.tool()
def divide(a: float, b: float) -> float:
    """两数相除"""
    if b == 0:
        raise ValueError("除数不能为零")
    return a / b

# MCP数学计算服务增强模块

@mcp.tool()
def power(base: float, exponent: float) -> float:
    """幂运算计算器"""
    if base == 0 and exponent < 0:
        raise ValueError("0的负指数次幂未定义")
    return base ** exponent

@mcp.tool()
def factorial(n: int) -> int:
    """阶乘计算器"""
    if not isinstance(n, int) or n < 0:
        raise ValueError("阶乘参数必须为非负整数")
    if n > 1000:
        raise ValueError("阶乘参数过大(>1000)，可能造成性能问题")
    return 1 if n == 0 else n * factorial(n-1)

@mcp.tool()
def sqrt(number: float) -> float:
    """平方根计算器"""
    if not isinstance(number, (int, float)):
        raise TypeError("输入必须为数字类型")
    if number < 0:
        raise ValueError("负数没有实数平方根")
    guess = number / 2 if number > 1 else number * 2
    while abs(guess*guess - number) > 1e-9:
        guess = (guess + number/guess) / 2
    return guess

@mcp.tool()
def log(x: float, base: float = 10.0) -> float:
    """对数计算器"""
    if x <= 0 or base <= 0 or base == 1:
        raise ValueError("参数必须满足x>0且base>0且base≠1")
    import math
    return math.log(x, base)

@mcp.tool()
def sin(radians: float) -> float:
    """正弦函数计算器"""
    import math
    return math.sin(radians)

@mcp.tool()
def cos(radians: float) -> float:
    """余弦函数计算器"""
    import math
    return math.cos(radians)

@mcp.tool()
def tan(radians: float) -> float:
    """正切函数计算器"""
    import math
    if abs(radians % math.pi - math.pi/2) < 1e-9:
        raise ValueError("正切函数在π/2+kπ处无定义")
    return math.tan(radians)

if __name__ == "__main__":
    # 使用stdio传输方式运行服务器
    mcp.run(transport="stdio")